const db = require('../config/database');
const logger = require('../config/logger');

/**
 * 获取软件分类列表
 */
exports.getCategories = async (req, res) => {
  try {
    const [categories] = await db.query(
      'SELECT * FROM software_categories ORDER BY sort_order ASC, id ASC'
    );

    res.json({
      success: true,
      data: categories
    });
  } catch (error) {
    logger.error('获取软件分类失败:', error);
    res.status(500).json({
      success: false,
      message: '获取软件分类失败'
    });
  }
};

/**
 * 获取软件列表
 */
exports.getSoftwareList = async (req, res) => {
  try {
    const { categoryId, keyword, page = 1, limit = 20 } = req.query;
    const offset = (page - 1) * limit;

    let query = `
      SELECT 
        s.*,
        c.name as category_name,
        c.icon as category_icon
      FROM software s
      LEFT JOIN software_categories c ON s.category_id = c.id
      WHERE s.status = 'active'
    `;

    let countQuery = 'SELECT COUNT(*) as total FROM software s WHERE s.status = "active"';
    const params = [];

    // 分类筛选
    if (categoryId) {
      query += ' AND s.category_id = ?';
      countQuery += ' AND s.category_id = ?';
      params.push(categoryId);
    }

    // 关键字搜索
    if (keyword) {
      query += ' AND (s.name LIKE ? OR s.description LIKE ?)';
      countQuery += ' AND (s.name LIKE ? OR s.description LIKE ?)';
      const searchTerm = `%${keyword}%`;
      params.push(searchTerm, searchTerm);
    }

    // 获取总数
    const [countResult] = await db.query(countQuery, params);
    const total = countResult[0].total;

    // 添加排序和分页
    query += ' ORDER BY s.download_count DESC, s.created_at DESC LIMIT ? OFFSET ?';
    params.push(parseInt(limit), offset);

    const [software] = await db.query(query, params);

    res.json({
      success: true,
      data: {
        software,
        total,
        page: parseInt(page),
        limit: parseInt(limit)
      }
    });
  } catch (error) {
    logger.error('获取软件列表失败:', error);
    res.status(500).json({
      success: false,
      message: '获取软件列表失败'
    });
  }
};

/**
 * 获取软件详情
 */
exports.getSoftwareDetail = async (req, res) => {
  try {
    const { id } = req.params;

    const [software] = await db.query(
      `SELECT 
        s.*,
        c.name as category_name,
        c.icon as category_icon,
        f.file_name,
        f.file_path
      FROM software s
      LEFT JOIN software_categories c ON s.category_id = c.id
      LEFT JOIN files f ON s.file_id = f.id
      WHERE s.id = ? AND s.status = 'active'`,
      [id]
    );

    if (software.length === 0) {
      return res.status(404).json({
        success: false,
        message: '软件不存在'
      });
    }

    res.json({
      success: true,
      data: software[0]
    });
  } catch (error) {
    logger.error('获取软件详情失败:', error);
    res.status(500).json({
      success: false,
      message: '获取软件详情失败'
    });
  }
};

/**
 * 创建软件（管理员）
 */
exports.createSoftware = async (req, res) => {
  try {
    const {
      name,
      version,
      categoryId,
      description,
      fileId,
      fileSize,
      iconUrl,
      screenshotUrls,
      developer,
      website
    } = req.body;

    const [result] = await db.query(
      `INSERT INTO software 
      (name, version, category_id, description, file_id, file_size, icon_url, screenshot_urls, developer, website, created_at) 
      VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())`,
      [name, version, categoryId, description, fileId, fileSize, iconUrl, screenshotUrls, developer, website]
    );

    logger.info(`创建软件: ${name}, ID: ${result.insertId}`);

    res.json({
      success: true,
      message: '软件创建成功',
      data: { id: result.insertId }
    });
  } catch (error) {
    logger.error('创建软件失败:', error);
    res.status(500).json({
      success: false,
      message: '创建软件失败'
    });
  }
};

/**
 * 更新软件（管理员）
 */
exports.updateSoftware = async (req, res) => {
  try {
    const { id } = req.params;
    const updates = req.body;

    const allowedFields = [
      'name', 'version', 'category_id', 'description', 'file_id', 'file_size',
      'icon_url', 'screenshot_urls', 'developer', 'website', 'status'
    ];

    const setFields = [];
    const values = [];

    Object.keys(updates).forEach(key => {
      const snakeKey = key.replace(/([A-Z])/g, '_$1').toLowerCase();
      if (allowedFields.includes(snakeKey)) {
        setFields.push(`${snakeKey} = ?`);
        values.push(updates[key]);
      }
    });

    if (setFields.length === 0) {
      return res.status(400).json({
        success: false,
        message: '没有可更新的字段'
      });
    }

    values.push(id);

    await db.query(
      `UPDATE software SET ${setFields.join(', ')}, updated_at = NOW() WHERE id = ?`,
      values
    );

    logger.info(`更新软件: ID ${id}`);

    res.json({
      success: true,
      message: '软件更新成功'
    });
  } catch (error) {
    logger.error('更新软件失败:', error);
    res.status(500).json({
      success: false,
      message: '更新软件失败'
    });
  }
};

/**
 * 删除软件（管理员）
 */
exports.deleteSoftware = async (req, res) => {
  try {
    const { id } = req.params;

    await db.query(
      'UPDATE software SET status = "disabled", updated_at = NOW() WHERE id = ?',
      [id]
    );

    logger.info(`删除软件: ID ${id}`);

    res.json({
      success: true,
      message: '软件删除成功'
    });
  } catch (error) {
    logger.error('删除软件失败:', error);
    res.status(500).json({
      success: false,
      message: '删除软件失败'
    });
  }
};

/**
 * 下载软件（增加下载计数）
 */
exports.downloadSoftware = async (req, res) => {
  try {
    const { id } = req.params;

    // 获取软件信息
    const [software] = await db.query(
      `SELECT s.*, f.file_path 
       FROM software s 
       LEFT JOIN files f ON s.file_id = f.id 
       WHERE s.id = ? AND s.status = 'active'`,
      [id]
    );

    if (software.length === 0) {
      return res.status(404).json({
        success: false,
        message: '软件不存在'
      });
    }

    if (!software[0].file_path) {
      return res.status(400).json({
        success: false,
        message: '软件文件不存在'
      });
    }

    // 增加下载计数
    await db.query(
      'UPDATE software SET download_count = download_count + 1 WHERE id = ?',
      [id]
    );

    logger.info(`下载软件: ${software[0].name}, 用户: ${req.user.username}`);

    // 返回下载URL或文件路径
    res.json({
      success: true,
      data: {
        downloadUrl: `/api/files/download/${software[0].file_id}`,
        fileName: software[0].name + (software[0].version ? `-${software[0].version}` : '')
      }
    });
  } catch (error) {
    logger.error('下载软件失败:', error);
    res.status(500).json({
      success: false,
      message: '下载软件失败'
    });
  }
};

/**
 * 获取热门软件
 */
exports.getPopularSoftware = async (req, res) => {
  try {
    const { limit = 10 } = req.query;

    const [software] = await db.query(
      `SELECT 
        s.*,
        c.name as category_name,
        c.icon as category_icon
      FROM software s
      LEFT JOIN software_categories c ON s.category_id = c.id
      WHERE s.status = 'active'
      ORDER BY s.download_count DESC
      LIMIT ?`,
      [parseInt(limit)]
    );

    res.json({
      success: true,
      data: software
    });
  } catch (error) {
    logger.error('获取热门软件失败:', error);
    res.status(500).json({
      success: false,
      message: '获取热门软件失败'
    });
  }
};
